#!/usr/bin/env python
import os
import sys
import win32com.client

def print_usage():
    print("使用方法:")
    print("1. 在当前目录下创建一个名为 'rtf' 的文件夹（可以包含子目录，用于组织待转换文件）")
    print("2. 将需要转换的 RTF 文件放入该文件夹或其任意子目录")
    print("3. 运行脚本：python mian.py")
    print("-----------------------------------------")

# Converting Function
def ConvertRtfToDocsx(full_path):
    try:
        word = win32com.client.gencache.EnsureDispatch("Word.Application")
        word.Visible = False
        wdFormatDocumentDefault = 16
        doc = word.Documents.Open(full_path)
        for pic in doc.InlineShapes:
            try:
                pic.LinkFormat.SavePictureWithDocument = True
            except:
                pass
        doc.SaveAs(str(full_path.split(".")[0] + ".docx"), FileFormat=wdFormatDocumentDefault)
        doc.Close()
        word.Quit()
        return True
    except Exception:
        return False

# 递归扫描目录并转换 RTF 文件（包含子目录）
def scanner(root_dir):
    for path, dirs, files in os.walk(root_dir):
        for file in files:
            full_path = os.path.join(path, file)
            if file.split(".")[-1].lower() == "rtf":
                if ConvertRtfToDocsx(full_path):
                    os.remove(full_path)
                    docx_path = full_path.split(".")[0] + ".docx"
                    print(f"转换成功: {full_path} -> {docx_path}")
                else:
                    print(f"{full_path}: 转换失败")

if __name__ == '__main__':
    print_usage()
    current_dir = os.getcwd()
    rtf_folder = os.path.join(current_dir, 'rtf')
    if os.path.exists(rtf_folder):
        scanner(rtf_folder)
        print("\n转换完成！所有成功转换的 RTF 文件已被删除")
    else:
        print("当前目录不存在 rtf 文件夹!")
    sys.exit(0)
